<template>
  <div class="Article-List">
    <van-pull-refresh v-model="refreshLoading" @refresh="onRefresh" :success-text="refreshSuccessText" success-duration="1000">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error" error-text="请求失败，点击重新加载">
        <!-- <van-cell v-for="(Article, index) in list" :key="index" :title="Article.title" /> -->
        <ArticleItem v-for="(Article, index) in list" :key="index" :Article="Article"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { ArticleListAPI } from '@/api/ArticleList.js'
import ArticleItem from '@/components/article-item/index.vue'
export default {
  name: 'ArticleList',
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [], //储存列表数据的数组
      loading: false, //控制加载中loading状态
      finished: false, //控制数据加载结束的状态
      timestamp: null, //请求获取下一页数据的时间戳
      error: false, //控制列表加载失败的提示状态
      refreshLoading: false, //控制下拉刷新 设置为 false，表示加载完成
      refreshSuccessText: ''
    }
  },
  methods: {
    async onLoad() {
      try {
        // 1. 请求获取数据
        const { data } = await ArticleListAPI({
          channel_id: this.item.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 0
        })
        // console.log(data)
        // 2. 把请求结果数据放到 list 数组中
        // const { result } = data.data
        // this.list.push(...result)
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        this.list.push(...results)
        this.loading = false

        // 3. 本次数据加载结束之后要把加载状态设置为结束
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        // console.log('请求失败', err)
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        // 1. 请求获取数据
        const { data } = await ArticleListAPI({
          channel_id: this.item.id,
          timestamp: Date.now(),
          with_top: 0
        })
        // if (Math.random() > 0.2) {
        //   JSON.parse('asdas')
        // }

        // 2. 将数据追加到列表的顶部
        const { results } = data.data
        this.list.unshift(...results)
        // 3. 关闭下拉刷新的 loading 状态
        this.refreshLoading = false
        // 4. 判断数据是否全部加载完成
        this.refreshSuccessText = `刷新成功,更新了${results.length}条数据`
      } catch (err) {
        console.log(err)
        this.refreshSuccessText = `刷新失败`
        this.refreshLoading = false // 关闭下拉刷新的 loading 状态
        this.$toast('刷新失败')
      }
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.Article-List {
  height: 79vh;
  overflow-y: auto;
}
</style>
